<?php declare(strict_types=1);

namespace Zyucv7\Core\ORM;

/**
 * 数据分页类
 */
class Pager
{
    /** @var int 总记录数 */
    private $totalItems;

    /** @var int 当前页码 */
    private $currentPage;

    /** @var int 每页显示数量 */
    private $itemsPerPage;

    /** @var int 总页数 */
    private $totalPages;

    /** @var int 数据偏移量 */
    private $offset;

    /**
     * 构造函数
     * @param int $totalItems 总记录数
     * @param int $currentPage 当前页码
     * @param int $itemsPerPage 每页显示数量
     */
    public function __construct(int $totalItems, int $currentPage = 1, int $itemsPerPage = 10)
    {
        $this->totalItems = max(0, $totalItems);
        $this->itemsPerPage = max(1, $itemsPerPage);
        $this->totalPages = $this->calculateTotalPages();
        $this->currentPage = $this->validateCurrentPage($currentPage);
        $this->offset = $this->calculateOffset();
    }

    /**
     * 计算总页数
     * @return int
     */
    private function calculateTotalPages(): int
    {
        return $this->itemsPerPage > 0 
            ? (int) ceil($this->totalItems / $this->itemsPerPage) 
            : 0;
    }

    /**
     * 验证当前页码
     * @param int $page
     * @return int
     */
    private function validateCurrentPage(int $page): int
    {
        if ($page < 1) {
            return 1;
        }
        if ($page > $this->totalPages && $this->totalPages > 0) {
            return $this->totalPages;
        }
        return $page;
    }

    /**
     * 计算数据偏移量
     * @return int
     */
    private function calculateOffset(): int
    {
        return ($this->currentPage - 1) * $this->itemsPerPage;
    }

    /**
     * 获取分页信息
     * @return array
     */
    public function getPaginationInfo(): array
    {
        return [
            'total_items' => $this->totalItems,
            'current_page' => $this->currentPage,
            'items_per_page' => $this->itemsPerPage,
            'total_pages' => $this->totalPages,
            'offset' => $this->offset,
            'has_previous' => $this->currentPage > 1,
            'has_next' => $this->currentPage < $this->totalPages,
        ];
    }

    // Getter 方法
    public function getTotalItems(): int { return $this->totalItems; }
    public function getCurrentPage(): int { return $this->currentPage; }
    public function getItemsPerPage(): int { return $this->itemsPerPage; }
    public function getTotalPages(): int { return $this->totalPages; }
    public function getOffset(): int { return $this->offset; }
}